import { NameSpace } from 'utils';
import exceed from 'utils/apimap';

const { organization } = window.FORCE;

const ns = NameSpace('auditLog');
export const RECEIVE_AUDIT_DATA = ns('RECEIVE_AUDIT_DATA');
export const SET_TAB_KEY = ns('SET_TAB_KEY');
export const SET_CLEAR_DATA = ns('SET_CLEAR_DATA');
export const SET_TBUSER_DATA = ns('SET_TBUSER_DATA');
export const SET_DATE_DATA = ns('SET_DATE_DATA');
export const RECEIVE_DATE_DATA = ns('RECEIVE_DATE_DATA');
export const SET_ENTITY_DATA = ns('SET_ENTITY_DATA');
export const SET_REPO_DATA = ns('SET_REPO_DATA');
export const SET_GROUP_DATA = ns('SET_GROUP_DATA');
export const SET_TYPE_DATA = ns('SET_TYPE_DATA');
export const SET_TYPE_FILTER_DATA = ns('SET_TYPE_FILTER_DATA');
export const LOADING = ns('LOADING');
export const RECEIVE_PROJECT = ns('RECEIVE_PROJECT');
export const RECEIVE_GROUP = ns('RECEIVE_GROUP');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');
export const RESET_PROJECT = ns('RESET_PROJECT');
export const SET_SLS_DATA = ns('SET_SLS_DATA');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

export function resetProjects() {
  return (dispatch) => {
    dispatch({
      type: RESET_PROJECT,
    });
  };
}

// 审计日志
export function getAuditData(page, per_page) {
  return (dispatch, getState) => {
    dispatch({
      type: LOADING,
      data: true,
    });
    if (per_page) {
      dispatch({
        type: UPDATE_DATA,
        data: {
          pageSize: per_page,
        },
      });
    }

    const state = getState().organization.settings.audit;
    const { tabKey, paramsData, pageSize } = state;
    const {
      tb_user_ids,
      type,
      project_id,
      group_id,
      start_time,
      end_time,
      entity_id,
      entity_type,
      audit_filter_type,
    } = paramsData;

    exceed
      .fetch({
        api: 'organization.audit.log.get',
        params: {
          id: organization.id,
        },
        data: {
          page,
          per_page: per_page || pageSize || 10,
          type,
          start_time,
          end_time,
          entity_type,
          project_id: project_id && project_id.join(','),
          group_id: group_id && group_id.join(','),
          tb_user_ids: tb_user_ids && tb_user_ids.map((item) => item._userId).join(','),
          entity_id: entity_id && entity_id.map((item) => item._userId).join(','),
          include_sub_group: tabKey === 'group',
          audit_filter_type,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_AUDIT_DATA,
          data: Object.assign(
            { [tabKey]: result },
            {
              currentPage: page,
            },
          ),
        });

        dispatch({
          type: LOADING,
          data: false,
        });
      })
      .catch(() => {
        dispatch({
          type: LOADING,
          data: false,
        });
      });
  };
}

export function setClearData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_CLEAR_DATA,
      data,
    });
    dispatch(getAuditData(1));
  };
}

export function setTBUserData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_TBUSER_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setEntityUserData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_ENTITY_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setDateData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_DATE_DATA,
      data,
    });
  };
}

export function getDateData(data) {
  return (dispatch) => {
    dispatch({
      type: RECEIVE_DATE_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setTypeData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_TYPE_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setTypeFilterData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_TYPE_FILTER_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setRepoData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_REPO_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setGroupData(data) {
  return (dispatch) => {
    dispatch({
      type: SET_GROUP_DATA,
      data,
    });

    dispatch(getAuditData(1));
  };
}

export function setTabKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_TAB_KEY,
      data,
    });
    if (data !== 'organization') {
      dispatch(getProjectOrGroupData('group'));
      dispatch(getProjectOrGroupData('project'));
    }
    dispatch(getAuditData(1));
  };
}

export function getProjectOrGroupData(operateType, search) {
  return (dispatch, getState) => {
    const state = getState().organization.settings.audit;
    const { tabKey, paramsData } = state;
    const { group_id } = paramsData;

    let type;
    if (tabKey === 'project') {
      type = [
        'NEW_REPO',
        'DEL_REPO',
        'TRANSFER_REPO',
        'MOD_VISIBILITY',
        'MOD_MEMBER',
        'RESTORE_REPO',
      ].join(',');
    } else if (tabKey === 'repo') {
      type = ['HTTP_CLONE', 'SSH_CLONE', 'DOWNLOAD'].join(',');
    } else if (tabKey === 'group') {
      type = [
        'NEW_GROUP',
        'DEL_GROUP',
        'TRANSFER_GROUP',
        'MOD_GROUP_VISIBILITY',
        'MOD_GROUP_MEMBER',
        'RESTORE_GROUP',
      ].join(',');
    }
    exceed
      .fetch({
        api: `${operateType === 'project' ? 'projects' : 'groups'}.audit.log.get`,
        params: {
          org_id: organization.id,
        },
        data: {
          group_id: operateType === 'project' ? group_id && group_id.join(',') : '',
          search,
          page: 1,
          per_page: 5,
          type,
          order_by: 'last_activity_at',
        },
      })
      .then((data) => {
        data.shift();
        dispatch({
          type: operateType === 'project' ? RECEIVE_PROJECT : RECEIVE_GROUP,
          data,
        });
      });
  };
}

// 查询sls授权状态
export function getAuthorizationStatus() {
  return (dispatch) => {
    dispatch({
      type: SET_SLS_DATA,
      data: {
        isSlsAuthLoading: true,
      },
    });
    exceed
      .fetch({
        api: 'organization.settings.audit.sls.getAuthStatus',
        params: {
          organizationId: organization.id,
        },
        data: {
          role: 'AliyunRDCCodeAuditRole',
          organizationId: organization.id,
        },
      })
      .then((result) => {
        result.isSlsAuthLoading = false;
        dispatch({
          type: SET_SLS_DATA,
          data: result,
        });
      })
      .catch(() => {
        dispatch({
          type: SET_SLS_DATA,
          data: {
            isSlsAuthLoading: false,
          },
        });
      });
  };
}

// sls授权
export function slsAuthorize(role) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'organization.settings.audit.sls.authorize',
        params: {
          organizationId: organization.id,
        },
        data: {
          role,
          organizationId: organization.id,
        },
      })
      .then(() => {
        dispatch(getAuthorizationStatus());
      })
      .catch(() => {});
  };
}

// sls解除授权
export function removeAuth(authorizationId) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'organization.settings.audit.sls.removeAuth',
        params: {
          organizationId: organization.id,
        },
        data: {
          serviceAuthorizationId: authorizationId,
          organizationId: organization.id,
        },
      })
      .then(() => {
        dispatch(getAuthorizationStatus());
      })
      .catch(() => {});
  };
}
